﻿
using System;
using UnityEngine;

public class FlyObject : MonoBehaviour
{
    public Creature Target;
    public Rigidbody _rig;
    public SphereCollider _collider;
    public Action<FlyObject,Creature> HitCallback;

    private float _speed;//速度
    private float _radius;//碰撞体半径
    private Creature _caster;

    
    public void Init(Creature caster,Creature curTarget, float speed, float radius, Action<FlyObject, Creature> hitCalllback)
    {
        
        Target =curTarget;
        _caster = caster;
        _speed = speed;
        _radius = radius;
        HitCallback = hitCalllback;

        
        _rig = gameObject.AddComponent<Rigidbody>();
        _rig.useGravity = false;

        _collider = gameObject.AddComponent<SphereCollider>();
        _collider.radius = _radius;
        _collider.isTrigger = true;
    }

  

    void Update()
    {
        if (Target == null) { return; }
        _rig.velocity = (Target.transform.position - transform.position).normalized*_speed;
       
    }

  

    private void OnTriggerEnter(Collider other)
    {
        
        if (Target == null) { return; }
        if (other.transform != Target.gameObject.transform) { return; }
        Debug.Log("发生碰撞" + other.gameObject.name);

        Creature creature=other.gameObject.GetComponent<Creature>();
        if (creature != Target||!creature.CanBeAttack(_caster))
        {
            return;
        }
        
        if (HitCallback != null) { HitCallback(this,creature); }


    }
}
